/*
 * @lc app=leetcode.cn id=1609 lang=typescript
 *
 * [1609] 奇偶树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

class Node1609 {
  constructor(public node: TreeNode, public level: number) {
    this.node = node;
    this.level = level;
  }
}

function isEvenOddTree(root: TreeNode | null): boolean {
  if (root === null) return true;
  const deque = new Array<Node1609 | null>();
  deque.push(new Node1609(root, 0));

  while (deque.length) {
    const top = deque.shift();
    // 节点值与层数奇偶性不符
    if (top.node.val % 2 === top.level % 2) return false;
    // 偶数层要严格递增
    if (top.level % 2 === 0 && deque.length) {
      if (top.node.val >= deque[0].node.val && top.level === deque[0].level) return false;
    }
    // 奇数层要严格递减
    if (top.level % 2 === 1 && deque.length) {
      if (top.node.val <= deque[0].node.val && top.level === deque[0].level) return false;
    }
    if (top.node.left) deque.push(new Node1609(top.node.left, top.level + 1));
    if (top.node.right) deque.push(new Node1609(top.node.right, top.level + 1));
  }

  return true;
}
// @lc code=end
